import { useState, useEffect, useCallback } from "react";
import "./organization.css"
import {
  Skeleton, Tree, Input, Table, Space, Tag, Button, Modal,
  Form, message, Switch, Avatar
} from "antd";
import {
  DownOutlined, PlusOutlined, TeamOutlined, DeleteOutlined,
  UserOutlined
} from '@ant-design/icons';
import { AddDept } from "../../component/organization/AddDept";
import { AddEmployee } from "../../component/organization/AddEmployee";
import { EmployeeDetails } from "../../component/organization/EmployeeDetails";
import { ChangeIsBan_Employee, Delete_Dept, Get_Dept, Get_Dept_Employee } from "../../service/organization";

const { Search } = Input;

// 防抖函数
const debounce = (func, delay = 300) => {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
};

export const Dept = () => {
  // 状态管理
  const [isShow, setIsShow] = useState(true);
  const [selectedDept, setSelectedDept] = useState({ id: "", name: "" });
  const [searchValue, setSearchValue] = useState('');
  const [loadingEmployees, setLoadingEmployees] = useState(false);
  
  // 模态框状态
  const [addDeptVisible, setAddDeptVisible] = useState(false);
  const [addEmpVisible, setAddEmpVisible] = useState(false);
  const [empDetailVisible, setEmpDetailVisible] = useState(false);
  const [currentEmp, setCurrentEmp] = useState(null);
  
  // 部门数据和员工数据
  const [treeData, setTreeData] = useState([]);
  const [employeeData, setEmployeeData] = useState([]);

  // 分页参数管理 - 简化状态结构
  const [pagination, setPagination] = useState({
    current: 1,        // 当前页码
    pageSize: 10,      // 每页条数（调整为更合理的默认值）
    total: 0,          // 总数据条数
  });

  // 表单实例
  const [deptForm] = Form.useForm();

  // 处理部门删除
  const handleDeleteDept = (deptId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个部门吗？删除后部门下的员工将需要重新分配',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await Delete_Dept({ id: deptId });
          if (res.code === 0) {
            message.success('部门删除成功');
            Bind_Dept();
            if (selectedDept.id === deptId) {
              setSelectedDept({ id: "", name: "" });
              setEmployeeData([]);
            }
          } else {
            message.error('删除失败: ' + (res.msg || '未知错误'));
          }
        } catch (error) {
          console.error('删除部门出错:', error);
          message.error('删除部门时发生错误');
        }
      }
    });
  };

  // 格式化树形数据
  const formatTreeData = (data) => {
    return data.map(node => {
      const deptName = node.title;
      return {
        ...node,
        deptName: deptName,
        title: (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
            <span style={{ display: 'flex', alignItems: 'center' }}>
              <TeamOutlined />
              <span style={{ marginLeft: 8 }}>{deptName}({node.count})</span>
            </span>
            {node.count === 0 && (
              <DeleteOutlined
                className="delete-icon"
                style={{ marginTop: 2, cursor: 'pointer' }}
                onClick={(e) => {
                  e.stopPropagation();
                  handleDeleteDept(node.key);
                }}
              />
            )}
          </div>
        ),
        className: "dept-tree-node",
        ...(node.children && { children: formatTreeData(node.children) })
      };
    });
  };

  // 获取部门数据
  const Bind_Dept = async () => {
    try {
      const res = await Get_Dept();
      if (res.code === 0) {
        const formattedData = formatTreeData(res.data);
        setTreeData(formattedData);
      }
    } catch (error) {
      console.error('获取部门数据失败:', error);
      message.error('获取部门信息失败');
    }
  };

  // 初始化加载部门数据
  useEffect(() => {
    Bind_Dept();
  }, []);

  // 加载部门员工数据（使用useCallback优化）
  const loadEmployeesByDept = useCallback(async (deptId, searchKey = searchValue, pageInfo = pagination) => {
    if (!deptId) return;

    const { current: page, pageSize: limit } = pageInfo;
    setLoadingEmployees(true);
    
    try {
      const res = await Get_Dept_Employee({ 
        id: deptId, 
        key: searchKey, 
        page: page,
        limit: limit
      });

      if (res.code === 0) {
        setEmployeeData(res.data.data || []);
        // 更新分页信息
        setPagination(prev => ({
          ...prev,
          total: res.data.total || 0
        }));
      } else {
        message.error('获取员工数据失败: ' + (res.msg || '未知错误'));
        setEmployeeData([]);
        setPagination(prev => ({ ...prev, total: 0 }));
      }
    } catch (error) {
      console.error('加载员工数据出错:', error);
      message.error('加载员工数据时发生错误');
      setEmployeeData([]);
    } finally {
      setLoadingEmployees(false);
    }
  }, [searchValue, pagination]);

  // 选择部门后加载员工数据
  useEffect(() => {
    if (selectedDept && selectedDept.id) {
      // 重置到第一页
      setPagination(prev => ({ ...prev, current: 1 }));
      // 使用setTimeout确保状态更新后再加载数据
      setTimeout(() => {
        loadEmployeesByDept(selectedDept.id, searchValue, { ...pagination, current: 1 });
      }, 0);
    }
  }, [selectedDept]);

  // 分页参数或搜索值变化时重新加载数据
  useEffect(() => {
    if (selectedDept.id) {
      loadEmployeesByDept(selectedDept.id);
    }
  }, [pagination.current, pagination.pageSize, searchValue]);

  // 初始加载第一个部门数据
  useEffect(() => {
    if (treeData.length > 0) {
      const timer = setTimeout(() => {
        setIsShow(false);
        const firstDept = treeData[0];
        setSelectedDept({
          id: firstDept.key,
          name: firstDept.deptName
        });
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, [treeData]);

  // 表格列定义
  const columns = [
    {
      title: '账号',
      dataIndex: 'account',
      key: 'account',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <Avatar src={record.photo || <UserOutlined />} />
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '所属部门',
      dataIndex: 'deptName',
      key: 'deptName',
    },
    {
      title: '职称/岗位',
      dataIndex: 'postName',
      key: 'postName',
    },
    {
      title: '员工状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        status === "在职" ?
          <Tag color="blue">{status}</Tag> :
          <Tag color="red">{status}</Tag>
      ),
    },
    {
      title: '账号状态',
      dataIndex: 'isBan',
      key: 'isBan',
      render: (isBan, record) => (
        <Switch
          size="small"
          checkedChildren="启用"
          unCheckedChildren="禁用"
          checked={isBan}
          onChange={(checked) => handleStatusChange(record.id, checked)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            onClick={() => {
              setCurrentEmp(record);
              setEmpDetailVisible(true);
            }}
          >
            查看详情
          </Button>
        </Space>
      ),
    },
  ];

  // 部门选择处理
  const onSelect = (selectedKeys, info) => {
    const selectedKey = selectedKeys[0] || '';
    const selectedNode = info.node;

    if (selectedNode && selectedKey) {
      setSelectedDept({
        id: selectedKey,
        name: selectedNode.deptName
      });
    }
  };

  // 搜索处理
  const onSearch = (value) => {
    setSearchValue(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 防抖处理搜索输入
  const handleSearchInputChange = debounce((value) => {
    setSearchValue(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  }, 300);

  // 账号状态切换
  const handleStatusChange = async (id, checked) => {
    try {
      const res = await ChangeIsBan_Employee({ id: id, isBan: checked });
      if (res.code === 0) {
        message.success(res.message || '状态更新成功');
        loadEmployeesByDept(selectedDept.id);
      } else {
        message.error(res.message || '状态更新失败');
      }
    } catch (error) {
      console.error('更新账号状态出错:', error);
      message.error('更新状态时发生错误');
    }
  };

  // 分页变化处理
  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
  };

  // 新增部门处理
  const handleAddDept = () => {
    deptForm.resetFields();
    setAddDeptVisible(true);
  };

  // 新增员工处理
  const handleAddEmp = () => {
    if (!selectedDept || !selectedDept.id) {
      message.warning('请先选择一个部门');
      return;
    }
    setAddEmpVisible(true);
  };

  // 部门添加成功后处理
  const handleDeptAdded = () => {
    setAddDeptVisible(false);
    Bind_Dept();
  };

  // 关闭部门添加模态框
  const handClose = () => {
    setAddDeptVisible(false);
    Bind_Dept();
  };

  // 员工添加成功后处理
  const handleEmpAdded = () => {
    setAddEmpVisible(false);
    Bind_Dept();
    loadEmployeesByDept(selectedDept.id);
  };

  // 表格分页配置
  const tablePagination = {
    ...pagination,
   
    showTotal: (total) => `共 ${total} 条数据`,
    pageSizeOptions: ['10', '20', '50'],
  };

  return (
    <div className="dept-container">
      {isShow ? (
        <Skeleton paragraph={{ rows: 10 }} active />
      ) : (
        <div className="dept-main">
          <div className="dept-left">
            <div className="tree-container">
              <Tree
                showLine
                switcherIcon={<DownOutlined />}
                defaultExpandedKeys={treeData.length > 0 ? [treeData[0].key] : []}
                defaultSelectedKeys={treeData.length > 0 ? [treeData[0].key] : []}
                onSelect={onSelect}
                treeData={treeData}
                className="dept-tree"
              />
            </div>
            <div className="addDept-btn">
              <Button
                size="small"
                style={{ width: "100%" }}
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAddDept}
              >
                新增部门
              </Button>
            </div>
          </div>

          <div className="dept-right">
            <div className="search-box">
              <div style={{ flex: 1, textAlign: "center" }}>
                <Search
                  placeholder="请输入员工姓名,按回车键搜索"
                  allowClear
                  onSearch={onSearch}
                  onChange={(e) => handleSearchInputChange(e.target.value)}
                  style={{ width: 400 }}
                />
              </div>
              <div>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={handleAddEmp}
                >
                  新增员工
                </Button>
              </div>
            </div>

            <div style={{ marginTop: 10 }}>
              <Table
                bordered
                columns={columns}
                dataSource={employeeData}
                pagination={tablePagination}
                locale={{ emptyText: "暂无员工数据" }}
                loading={loadingEmployees}
                onChange={handleTableChange}
                rowKey="id"
              />
            </div>
          </div>
        </div>
      )}

      {/* 模态框部分保持不变 */}
      <Modal
        title="新增部门"
        open={addDeptVisible}
        style={{ top: "50px" }}
        onCancel={() => setAddDeptVisible(false)}
        footer={null}
        destroyOnHidden
      >
        <AddDept onClose={handClose} data={selectedDept} onDeptAdded={handleDeptAdded} />
      </Modal>

      <Modal
        title="新增员工"
        open={addEmpVisible}
        onCancel={() => setAddEmpVisible(false)}
        style={{ top: "50px" }}
        width={700}
        destroyOnHidden
        footer={null}
      >
        <AddEmployee
          data={selectedDept}
          onEmpAdded={handleEmpAdded}
        />
      </Modal>

      <Modal
        title={`员工详情 - ${currentEmp?.name}`}
        open={empDetailVisible}
        onCancel={() => setEmpDetailVisible(false)}
        width={900}
        footer={null}
        destroyOnHidden
      >
        {currentEmp && (
          <EmployeeDetails 
            onClose={() => {
              setEmpDetailVisible(false);
              Bind_Dept();
              loadEmployeesByDept(selectedDept.id);
            }} 
            data={currentEmp} 
          />
        )}
      </Modal>
    </div>
  );
};